﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace 简单了解C_网络编程
{
    internal class Program
    {
        static void Main(string[] args)
        {
            ////1.创建服务端Socket, 使用IPV4，字节流，Tcp协议
            //Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            ////2. 服务端绑定本机IP 和 8888端口号
            //server.Bind(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8888));

            ////3.服务端开始监听，最多监听10个客户端
            //server.Listen(10);

            //Console.WriteLine("服务端，创建，绑定，监听准备完成");

            ////4.阻塞等待，接收客户端的连接
            //Socket client = server.Accept();

            //Console.WriteLine("客户端连接了");

            ////1.创建服务端Socket，使用IPV4，字节流，TCP协议
            //Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            ////2.客户端接收服务端
            //client.Connect(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8888));

            ////1.创建服务端Socket，使用IPV4，字节流，TCP协议
            //Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            ////2.服务端绑定本机IP和8888端口号
            //server.Bind(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8888));

            ////3.服务端开始监听
            //server.Listen(10);

            ////4.阻塞等待，接收客户端的连接
            //Socket client = server.Accept();

            //Console.WriteLine("此时，客户端连接了");

            ////5.阻塞等待客户端接收消息
            //byte[] buffer = new byte[1024];
            //int v = client.Receive(buffer);
            //Console.WriteLine("服务端：" + Encoding.UTF8.GetString(buffer, 0 , v));

            ////6.向客户端发送消息
            //server.Send(Encoding.UTF8.GetBytes("服务端发送来的消息"));

            //1.创建服务端，使用IPV4，字节流，TCP协议
            Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            //2.客户端连接服务端
            client.Connect(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8888));

            //3.客户端向服务端发送消息
            client.Send(Encoding.UTF8.GetBytes("向服务端发送消息"));

            //4.阻塞等待接收服务端的消息
            byte[] buffer = new byte[1024];
            int v = client.Receive(buffer);
            Console.WriteLine("服务端发来的消息: " + Encoding.UTF8.GetString(buffer, 0, v));
        }
    }
}